<template>
  <span >  
      <div>
          <span>当前位置： {{info.positionName || positionName}}</span>
          <el-button @click="submit(0)">取消</el-button>
          <el-button type="primary" @click="submit(1)">确定</el-button>
      </div>
      <el-amap-search-box class="search-box" :search-option="{citylimit: false}" :on-search-result="onSearchResult"></el-amap-search-box>
      <el-amap :events="{click: mapClick}" vid="amapDemo" :center="mapCenter" :zoom="12" class="amap-demo" >
        <el-amap-marker v-for="marker in markers" :position="marker"></el-amap-marker>
      </el-amap >
  </span>
</template>
<script>
import { getPositionName } from '@/api/kaoqin'
export default { 
    props: {
        position: {
            type: Array,
            default () {
                return [121.220922, 31.287889]
            }
        },
        positionName: String
    },
    data() { 
        return {
            info: {
                positionName: '',
                positionLongitude: '',
                positionLatitude: ''
            },
            markers: [],
            mapCenter: [121.216304, 31.289393]
        }
    },
    created() {
        this.mapCenter = this.position
        this.markers = [this.mapCenter]
        console.log(this.positionName)
    },
    methods: {
      addMarker: function() {
        let lng = 121.5 + Math.round(Math.random() * 1000) / 10000;
        let lat = 31.197646 + Math.round(Math.random() * 500) / 10000;
        this.markers.push([lng, lat]);
      },
      onSearchResult(pois) { 
        let latSum = 0;
        let lngSum = 0;
        if (pois.length > 0) {
          pois.forEach(poi => {
            let {lng, lat} = poi;
            lngSum += lng;
            latSum += lat;
            this.markers.push([poi.lng, poi.lat]);
          });
          let center = {
            lng: lngSum / pois.length,
            lat: latSum / pois.length
          };
          this.mapCenter = [center.lng, center.lat];
        }
      }, 
      submit(v) {
        if (v)
            this.$emit('submit', this.info)
        else
            this.$emit('cancel')
      },
      mapClick(params) { 
          this.mapCenter = [params.lnglat.lng, params.lnglat.lat]
        this.markers = [
            this.mapCenter
        ]
        getPositionName({location: params.lnglat.lng + "," + params.lnglat.lat}).then(res => { 
            if (res.data.regeocode && res.data.regeocode.formatted_address) { 
                this.info = {
                    positionName: res.data.regeocode.formatted_address,
                    positionLongitude: params.lnglat.lng,
                    positionLatitude: params.lnglat.lat
                }
            }
        })
      }
    }
}
</script>
